package com.yanqu.road.server.cmd.activity.rankunionwar.cross;

import com.yanqu.road.entity.activity.rankunionwar.config.RankUnionWarConfig;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.RankUnionWarProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.rankunionwar.RankUnionWarMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.GameProtocol;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Cmd(code = GameProtocol.S_RANKUNIONWAR_CROSS_NOTICE_SYNC, desc = "")
public class RankUnionWarCrossNoticeSyncCmd extends AbstractCommand {

    RankUnionWarProto.RankUnionWarCrossNoticeSyncMsg reqMsg;
    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        reqMsg = RankUnionWarProto.RankUnionWarCrossNoticeSyncMsg.parseFrom(packet.getBytes());
        return true;
    }

    @Override
    public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
        RankUnionWarConfig config = RankUnionWarMgr.getConfig();
        if (config == null || !ActivityMgr.activityInShowTime(config.getActivityInfo())) {
            ret = GameErrorCode.E_ACTIVITY_NO_FOUND;
            return;
        }
        Map<Integer,List<Long>> userSceneMap = RankUnionWarMgr.getUserSceneMap();
        for(RankUnionWarProto.RankUnionWarCrossNoticeMsg crossSyncMsg : reqMsg.getGameNoticesList()){
            int gameNo = crossSyncMsg.getGameNo();
            if(userSceneMap.containsKey(gameNo)){
                for(long userId : new ArrayList<>(userSceneMap.get(gameNo))){
                    GamePlayer gamePlayer = GamePlayerMgr.getOnlinePlayer(userId);
                    if(gamePlayer == null){
                        RankUnionWarMgr.removeUserScene(gameNo,userId);
                    }else{
                        RankUnionWarProto.RankUnionWarNoticeSyncMsg.Builder userSyncMsg = RankUnionWarProto.RankUnionWarNoticeSyncMsg.newBuilder();
                        userSyncMsg.setActivityId(reqMsg.getActivityId());
                        userSyncMsg.setGameNo(gameNo);
                        userSyncMsg.addAllNotices(crossSyncMsg.getNoticesList());
                        gamePlayer.sendPacket(ClientProtocol.U_RANKUNIONWAR_NOTICE_LIST, userSyncMsg);
                    }
                }
            }
        }
    }

    @Override
    public void sendData(GamePlayer player) {
        if (ret == 0) {
            return;
        }
    }
}
